// AWTGridLayout.cpp: implementation of the AWTGridLayout class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
//#include "AWTTest.h"
#include "AWTGridLayout.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

IMPLEMENT_DYNAMIC(AWTGridLayout, AWTLayout)

AWTGridLayout::AWTGridLayout()
{
	construct(1,0,5,5);
}

AWTGridLayout::AWTGridLayout(int rows, int cols)
{
	construct(rows,cols,5,5);
}

AWTGridLayout::AWTGridLayout(int rows, int cols, int hgap, int vgap)
{
	construct(rows,cols,hgap,vgap);
}

AWTGridLayout::~AWTGridLayout()
{
};

CSize AWTGridLayout::preferredLayoutSize(AWTContainer* parent)
{
	AWTInsets insets = parent->getInsets();
	int ncomponents = parent->getComponentCount();
	int nrows = m_rows;
	int ncols = m_cols;

	if (nrows > 0) 
		ncols = (ncomponents + nrows - 1) / nrows;
	else 
	  nrows = (ncomponents + ncols - 1) / ncols;

	int w = 0;
	int h = 0;
	for (int i = 0 ; i < ncomponents ; i++) 
	{
		AWTComponent* comp = parent->getComponent(i);
	  CSize d = comp->getPreferredSize();
	  if (w < d.cx) 
			w = d.cx;
	  if (h < d.cy) 
			h = d.cy;
	}
	return CSize(insets.left + insets.right + ncols*w + (ncols-1)*m_hgap, 
			     insets.top + insets.bottom + nrows*h + (nrows-1)*m_vgap);
}

CSize AWTGridLayout::minimumLayoutSize(AWTContainer* parent)
{
	AWTInsets insets = parent->getInsets();
	int ncomponents = parent->getComponentCount();
	int nrows = m_rows;
	int ncols = m_cols;

	if (nrows > 0) 
	  ncols = (ncomponents + nrows - 1) / nrows;
	else 
	  nrows = (ncomponents + ncols - 1) / ncols;
	
	int w = 0;
	int h = 0;
	for (int i = 0 ; i < ncomponents ; i++) 
	{
	  AWTComponent* comp = parent->getComponent(i);
	  CSize d = comp->getMinimumSize();
	  if (w < d.cx) 
			w = d.cx;
	  if (h < d.cy) 
			h = d.cy;
	}
	return CSize(insets.left + insets.right + ncols*w + (ncols-1)*m_hgap, 
			     insets.top + insets.bottom + nrows*h + (nrows-1)*m_vgap);
}

void AWTGridLayout::layoutContainer(AWTContainer* parent)
{
	AWTInsets insets = parent->getInsets();
	int ncomponents = parent->getComponentCount();
	int nrows = m_rows;
	int ncols = m_cols;

	if (ncomponents == 0) 
	  return;

	if (nrows > 0) 
	  ncols = (ncomponents + nrows - 1) / nrows;
	else 
	  nrows = (ncomponents + ncols - 1) / ncols;

	int w = parent->getWidth() - (insets.left + insets.right);
	int h = parent->getHeight() - (insets.top + insets.bottom);
	w = (w - (ncols - 1) * m_hgap) / ncols;
	h = (h - (nrows - 1) * m_vgap) / nrows;

	for (int c = 0, x = insets.left ; c < ncols ; c++, x += w + m_hgap) 
	{
		for (int r = 0, y = insets.top ; r < nrows ; r++, y += h + m_vgap) 
		{
			int i = r * ncols + c;
			if (i < ncomponents) 
			{
				parent->getComponent(i)->setBounds(x, y, w, h);
			}
	  }
	}
}
